<template>
  <div>
    <avue-crud
      :data="data.data"
      :option="option"
      :page="page"
      :sortable="true"
      @on-load="changePage"
      @row-save="create"
      @row-update="update"
      @row-del="remove"
      @sort-change="sortChange"
      @search-change="search"
    ></avue-crud>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';

@Component({})
export default class ResourceList extends Vue {
  @Prop(String) resource !: string;
  data: any = {};
  option: any = {};
  page: any = {
    pageSize: 2,
    pageSizes: [2, 8, 12, 16, 20, 30],
    total: 0,
  };

  query: any = {
    limit: 2,
  };

  async fetch() {
    const { data } = await this.$http.get(`${this.resource}`, {
      params: {
        query: this.query,
      },
    });
    this.page.total = data.total;
    this.data = data;
  }

  async changePage({ pageSize, currentPage }) {
    this.query.page = currentPage;
    this.query.limit = pageSize;
    this.fetch();
  }

  async sortChange({ prop, order }) {
    if (!order) {
      this.query.sort = null;
    } else {
      this.query.sort = {
        [prop]: order === 'ascending' ? 1 : -1,
      };
    }
    this.fetch();
  }

  async search(where,done) {
    for (let k in where) {
      const field = this.option.column.find(v => v.prop === k);
      if (field.regex) {
        where[k] = { $regex: where[k] };
      }
    }
    this.query.where = where;
    this.fetch();
    done()
  }

  async fetchOption() {
    const { data } = await this.$http.get(`${this.resource}/option`);
    this.option = data;
  }

  async create(row: any, done: any, loading: any) {
    await this.$http.post(`${this.resource}`, row);
    this.$message.success('创建成功');
    this.fetch();
    done();
  }

  async update(row: any, index: any, done: any, loading: any) {
    const data = JSON.parse(JSON.stringify(row));
    delete data.$index;
    await this.$http.put(`${this.resource}/${data._id}`, data);
    this.$message.success('创建成功');
    this.fetch();
    done();
  }

  async remove(row: any, index: any) {
    await this.$http.delete(`${this.resource}/${row._id}`);
    this.fetch();
    this.$message.success('成功');
  }
  
  created() {
    this.fetch();
    this.fetchOption();
  }
}
</script>